import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'

let timeout = 10000
const config = {
	baseUrl: 'https://www.daolangtongge.com/read-book-api',
	// baseUrl:'http://192.168.0.117:9009/read-book-api',
}
const baseUrl = config.baseUrl
let is401Handled = false

// 401白名单页面路径（支持模糊匹配）
const whiteList = [
	'pages/index/invitation', // vip分享页
	// 可以继续添加其他不需要跳转登录的页面
]

// 检查当前页面是否在白名单中
const isInWhiteList = () => {
	const pages = getCurrentPages()
	if (pages.length === 0) return false

	const currentPage = pages[pages.length - 1]
	const currentRoute = '/' + currentPage.route

	// 检查是否匹配白名单
	return whiteList.some(whitePath => {
		// 精确匹配或路径前缀匹配
		return currentRoute === whitePath || currentRoute.startsWith(whitePath + '/')
	})
}

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = 'Bearer ' + getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {
				const res = response
				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.msg || errorCode['default']
				if (code === 401) {
					// 检查是否在白名单中
					if (isInWhiteList()) {
						// 白名单页面，继续执行，让页面自己处理401
						resolve(res.data)
						return
					}

					// 非白名单页面，执行原来的跳转逻辑
					if (!is401Handled) {
						toast('登录已过期')
						is401Handled = true // 标记为已处理，防止重复弹窗
						uni.removeStorageSync('activity');
						uni.removeStorageSync('city');
						uni.removeStorageSync('App-Token');
						uni.setStorageSync('address', {
							value: '西安市'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/index/index',
								complete: () => {
									is401Handled = false // 跳转完成后重置标记
								}
							})
						}, 1000)
					}
					return // 终止当前Promise流程，不执行后续逻辑
				} else if (code === 500) {
					toast(msg)
					reject(code)
				} else if (code !== 200) {
					toast(msg)
					reject(code)
				}
				resolve(res.data)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
				reject(error)
			})
	})
}

export default request